<script setup lang="ts">
import type { ECharts, EChartsOption } from 'echarts'
import { init } from 'echarts'

interface Props {
  width?: string
  /** 高度 */
  height?: string
  /** 图表配置项 */
  option: EChartsOption
  /** 标题 */
  title?: string
  /** 简单模式 */
  simple?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  height: '100%',
  width: '100%',
})

const echartsRef = ref<HTMLDivElement>()
const isDark = useDark()

let myChart: ECharts
let timer: string | number | NodeJS.Timeout | undefined
// 初始化echarts
function initChart(): void {
  if (myChart !== undefined) {
    myChart.dispose()
  }
  myChart = init(echartsRef.value as HTMLDivElement, isDark.value ? 'dark' : 'light')
  // 拿到option配置项，渲染echarts
  myChart?.setOption(
    {
      backgroundColor: 'transparent',
      ...props.option,
    },
    true,
  )
}

// 重新渲染echarts
function resizeChart(): void {
  timer = setTimeout(() => {
    if (myChart) {
      myChart.resize()
    }
  }, 500)
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  clearTimeout(timer as any)
  timer = 0
})

watch(
  () => isDark,
  () => {
    initChart()
  },
  {
    deep: true,
  },
)

watch(
  props.option,
  () => {
    initChart()
  },
  {
    deep: true,
  },
)
</script>

<template>
  <el-card v-if="!simple" class="echarts-box">
    <div class="echarts-box-header">
      <slot name="title">
        <div
          class="title"
        >
          {{ title }}
        </div>
      </slot>
      <div class="right">
        <slot name="header" />
      </div>
    </div>
    <div ref="echartsRef" :style="{ height, width }" />
  </el-card>
  <div v-else ref="echartsRef" :style="{ height, width }" />
</template>

<style scoped>
.echarts-box {
  width: 100%;
  box-sizing: border-box;
  .echarts-box-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .title {
      font-size: 18px;
      font-weight: 550;
      color: var(--sy-text-color-primary);
    }
  }
}
</style>
